using FBroSharp.Const;
using FBroSharp.Event;
using System;
using System.IO;
using System.Text;

namespace 虾皮shopee电商数据采集
{
    /// <summary>
    /// HTTP响应拦截器 - 拦截并保存Shopee商品数据
    /// </summary>
    public class ResponseFilterEvent : FBroSharpResponseFilterEvent
    {
        //用于保存当前处理的资源地址
        public string url = "";

        //用于存放全部数据
        private MemoryStream responseStream;
        private BinaryWriter writer;
        private Form1 _form;

        public ResponseFilterEvent(Form1 form)
        {
            _form = form;
        }

        public override void Start(long flag)
        {
            responseStream = new MemoryStream();
            writer = new BinaryWriter(responseStream);
            Console.WriteLine($"[拦截器] 开始拦截: {url}");
        }

        //获取结束
        public override void End(long flag)
        {
            byte[] data = responseStream.ToArray();

            if (data != null && data.Length > 0)
            {
                try
                {
                    // 创建data目录
                    string dataPath = Path.Combine(Directory.GetCurrentDirectory(), "data");
                    if (!Directory.Exists(dataPath))
                    {
                        Directory.CreateDirectory(dataPath);
                    }

                    // 从URL中提取item_id作为文件名
                    string fileName = ExtractItemIdFromUrl(url);
                    if (string.IsNullOrEmpty(fileName))
                    {
                        fileName = $"shopee_{DateTime.Now:yyyyMMdd_HHmmss}";
                    }

                    // 保存JSON文件
                    string filePath = Path.Combine(dataPath, $"{fileName}.json");
                    File.WriteAllBytes(filePath, data);

                    // 转换为字符串用于显示
                    string jsonContent = Encoding.UTF8.GetString(data);

                    // 输出拦截信息到控制台
                    Console.WriteLine($"[拦截成功] URL: {url}");
                    Console.WriteLine($"[拦截成功] 大小: {data.Length} 字节");
                    Console.WriteLine($"[拦截成功] 保存到: {filePath}");
                    Console.WriteLine($"[拦截成功] 内容预览: {jsonContent.Substring(0, Math.Min(200, jsonContent.Length))}...");

                    // 通知主窗体更新UI
                    if (_form.InvokeRequired)
                    {
                        _form.Invoke(new Action(() => 
                        {
                            _form.AddInterceptedRequest(url, data.Length, filePath, jsonContent);
                        }));
                    }
                    else
                    {
                        _form.AddInterceptedRequest(url, data.Length, filePath, jsonContent);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[拦截器] 保存数据失败: {ex.Message}");
                }
            }

            responseStream?.Dispose();
            writer?.Dispose();
            responseStream = null;
            writer = null;
        }

        public override FBroSharpResponseFilterStatus Filter(long flag, Stream dataIn, out long dataInRead, Stream dataOut, out long dataOutWritten)
        {
            dataInRead = 0;
            dataOutWritten = 0;

            try
            {
                if (dataIn == null)
                {
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
                }

                //Calculate how much data we can read
                dataInRead = Math.Min(dataIn.Length, dataOut.Length);
                dataOutWritten = dataInRead;

                var readBytes = new byte[dataInRead];
                dataIn.Read(readBytes, 0, readBytes.Length);

                // ⚠️ 关键：确保数据立即传递给浏览器，避免阻塞
                dataOut.Write(readBytes, 0, readBytes.Length);
                dataOut.Flush();

                // ⚠️ 安全检查：避免内存溢出（限制10MB）
                if (responseStream != null && responseStream.Length > 10 * 1024 * 1024)
                {
                    Console.WriteLine($"[拦截器] 数据过大，停止收集: {url}");
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
                }

                //Write buffer to the memory stream
                writer?.Write(readBytes);

                //If we read less than the total amount available
                if (dataInRead < dataIn.Length)
                {
                    return FBroSharpResponseFilterStatus.RESPONSE_FILTER_NEED_MORE_DATA;
                }

                return FBroSharpResponseFilterStatus.RESPONSE_FILTER_DONE;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[拦截器] Filter错误: {ex.Message}");
                return FBroSharpResponseFilterStatus.RESPONSE_FILTER_ERROR;
            }
        }

        public override bool InitFilter(long flag)
        {
            //返回真开始拦截
            return true;
        }

        /// <summary>
        /// 从URL中提取item_id
        /// </summary>
        private string ExtractItemIdFromUrl(string url)
        {
            try
            {
                // 示例URL: https://shopee.tw/api/v4/pdp/get_pc?item_id=12345678&shop_id=87654321
                if (url.Contains("item_id="))
                {
                    int startIndex = url.IndexOf("item_id=") + 8;
                    int endIndex = url.IndexOf("&", startIndex);
                    if (endIndex == -1)
                    {
                        endIndex = url.Length;
                    }
                    string itemId = url.Substring(startIndex, endIndex - startIndex);
                    return $"item_{itemId}";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"[拦截器] 提取item_id失败: {ex.Message}");
            }
            return null;
        }
    }
}

